package com.smartcampusbackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.smartcampusbackend.mapper.SystemLogMapper;
import com.smartcampusbackend.model.SystemLog;
import com.smartcampusbackend.service.SystemLogService;
import com.smartcampusbackend.util.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class SystemLogServiceImpl implements SystemLogService {
    
    @Autowired
    private SystemLogMapper systemLogMapper;
    
    @Override
    public void log(SystemLog systemLog) {
        systemLog.setCreateTime(LocalDateTime.now());
        systemLogMapper.insert(systemLog);
    }
    
    @Override
    public void logLogin(String username, Integer userId, String ipAddress, String userAgent, String status, String description) {
        SystemLog systemLog = new SystemLog();
        systemLog.setUserId(userId);
        systemLog.setUsername(username);
        systemLog.setLogType("LOGIN");
        systemLog.setAction("用户登录");
        systemLog.setDescription(description);
        systemLog.setIpAddress(ipAddress);
        systemLog.setUserAgent(userAgent);
        systemLog.setRequestUrl("/api/auth/login");
        systemLog.setRequestMethod("POST");
        systemLog.setStatus(status);
        log(systemLog);
    }
    
    @Override
    public void logOperation(String username, Integer userId, String action, String description, String ipAddress, String userAgent, String requestUrl, String requestMethod, String requestParams, Integer responseStatus, Long executionTime, String status) {
        SystemLog systemLog = new SystemLog();
        systemLog.setUserId(userId);
        systemLog.setUsername(username);
        systemLog.setLogType("OPERATION");
        systemLog.setAction(action);
        systemLog.setDescription(description);
        systemLog.setIpAddress(ipAddress);
        systemLog.setUserAgent(userAgent);
        systemLog.setRequestUrl(requestUrl);
        systemLog.setRequestMethod(requestMethod);
        systemLog.setRequestParams(requestParams);
        systemLog.setResponseStatus(responseStatus);
        systemLog.setExecutionTime(executionTime);
        systemLog.setStatus(status);
        log(systemLog);
    }
    
    @Override
    public void logData(String username, Integer userId, String action, String description, String ipAddress, String userAgent, String requestUrl, String requestMethod, String requestParams, Integer responseStatus, Long executionTime, String status) {
        SystemLog systemLog = new SystemLog();
        systemLog.setUserId(userId);
        systemLog.setUsername(username);
        systemLog.setLogType("DATA");
        systemLog.setAction(action);
        systemLog.setDescription(description);
        systemLog.setIpAddress(ipAddress);
        systemLog.setUserAgent(userAgent);
        systemLog.setRequestUrl(requestUrl);
        systemLog.setRequestMethod(requestMethod);
        systemLog.setRequestParams(requestParams);
        systemLog.setResponseStatus(responseStatus);
        systemLog.setExecutionTime(executionTime);
        systemLog.setStatus(status);
        log(systemLog);
    }
    
    @Override
    public void logError(String username, Integer userId, String action, String description, String ipAddress, String userAgent, String requestUrl, String requestMethod, String requestParams, Integer responseStatus, String errorMessage, Long executionTime) {
        SystemLog systemLog = new SystemLog();
        systemLog.setUserId(userId);
        systemLog.setUsername(username);
        systemLog.setLogType("ERROR");
        systemLog.setAction(action);
        systemLog.setDescription(description);
        systemLog.setIpAddress(ipAddress);
        systemLog.setUserAgent(userAgent);
        systemLog.setRequestUrl(requestUrl);
        systemLog.setRequestMethod(requestMethod);
        systemLog.setRequestParams(requestParams);
        systemLog.setResponseStatus(responseStatus);
        systemLog.setErrorMessage(errorMessage);
        systemLog.setExecutionTime(executionTime);
        systemLog.setStatus("FAILED");
        log(systemLog);
    }
    
    @Override
    public IPage<SystemLog> getLogsByPage(Page<SystemLog> page, String username, String logType, String status, String startDate, String endDate) {
        QueryWrapper<SystemLog> queryWrapper = new QueryWrapper<>();
        
        if (username != null && !username.trim().isEmpty()) {
            queryWrapper.like("username", username);
        }
        
        if (logType != null && !logType.trim().isEmpty()) {
            queryWrapper.eq("log_type", logType);
        }
        
        if (status != null && !status.trim().isEmpty()) {
            queryWrapper.eq("status", status);
        }
        
        if (startDate != null && !startDate.trim().isEmpty()) {
            queryWrapper.ge("create_time", startDate + " 00:00:00");
        }
        
        if (endDate != null && !endDate.trim().isEmpty()) {
            queryWrapper.le("create_time", endDate + " 23:59:59");
        }
        
        queryWrapper.orderByDesc("create_time");
        
        return systemLogMapper.selectPage(page, queryWrapper);
    }
    
    @Override
    public Map<String, Object> getTodayStats() {
        return systemLogMapper.getTodayStats();
    }
    
    @Override
    public List<SystemLog> getRecentLogsByUsername(String username, int limit) {
        return systemLogMapper.getRecentLogsByUsername(username, limit);
    }
    
    @Override
    public List<Map<String, Object>> getLogStatsByDateRange(String startDate, String endDate) {
        return systemLogMapper.getLogStatsByDateRange(startDate, endDate);
    }
    
    @Override
    public byte[] exportLogs(String username, String logType, String status, String startDate, String endDate) {
        QueryWrapper<SystemLog> queryWrapper = new QueryWrapper<>();
        
        if (username != null && !username.trim().isEmpty()) {
            queryWrapper.like("username", username);
        }
        
        if (logType != null && !logType.trim().isEmpty()) {
            queryWrapper.eq("log_type", logType);
        }
        
        if (status != null && !status.trim().isEmpty()) {
            queryWrapper.eq("status", status);
        }
        
        if (startDate != null && !startDate.trim().isEmpty()) {
            queryWrapper.ge("create_time", startDate + " 00:00:00");
        }
        
        if (endDate != null && !endDate.trim().isEmpty()) {
            queryWrapper.le("create_time", endDate + " 23:59:59");
        }
        
        queryWrapper.orderByDesc("create_time");
        
        List<SystemLog> logs = systemLogMapper.selectList(queryWrapper);
        
        // 使用ExcelUtil导出
        String[] headers = {"ID", "用户名", "日志类型", "操作", "描述", "IP地址", "请求URL", "请求方法", "响应状态", "执行时间(ms)", "状态", "创建时间"};
        String[] fields = {"id", "username", "logType", "action", "description", "ipAddress", "requestUrl", "requestMethod", "responseStatus", "executionTime", "status", "createTime"};
        
        return ExcelUtil.exportToExcel("系统日志", headers, fields, logs);
    }
    
    @Override
    public byte[] exportLogsPDF(String username, String logType, String status, String startDate, String endDate) {
        QueryWrapper<SystemLog> queryWrapper = new QueryWrapper<>();
        
        if (username != null && !username.trim().isEmpty()) {
            queryWrapper.like("username", username);
        }
        
        if (logType != null && !logType.trim().isEmpty()) {
            queryWrapper.eq("log_type", logType);
        }
        
        if (status != null && !status.trim().isEmpty()) {
            queryWrapper.eq("status", status);
        }
        
        if (startDate != null && !startDate.trim().isEmpty()) {
            queryWrapper.ge("create_time", startDate + " 00:00:00");
        }
        
        if (endDate != null && !endDate.trim().isEmpty()) {
            queryWrapper.le("create_time", endDate + " 23:59:59");
        }
        
        queryWrapper.orderByDesc("create_time");
        
        List<SystemLog> logs = systemLogMapper.selectList(queryWrapper);
        
        // 暂时返回Excel数据，后续再实现PDF导出
        String[] headers = {"ID", "用户名", "日志类型", "操作", "描述", "IP地址", "请求URL", "请求方法", "响应状态", "执行时间(ms)", "状态", "创建时间"};
        String[] fields = {"id", "username", "logType", "action", "description", "ipAddress", "requestUrl", "requestMethod", "responseStatus", "executionTime", "status", "createTime"};
        
        return ExcelUtil.exportToExcel("系统日志", headers, fields, logs);
    }
} 